#include "Common.h"

bool MakeFifo()
{
    int n = mkfifo(FILENAME, 0666);
    if (n < 0)
    {
        cerr << "errno:" << errno << ",errstring" << strerror(errno) << endl;
        return 0;
    }
    cout << "mkfifo success..." << endl;
    return 1;
}

int main()
{

    int rfd = open(FILENAME, O_RDWR);
    if (rfd < 0)
    {
        cerr << "errno" << errno << ",ErrnoString:" << strerror(errno) << endl;
        if (MakeFifo())
        {
            cout << "The last Fifo not exist is solved\n";
            rfd = open(FILENAME, O_RDONLY);
        }
        else
            return 1;
    }
    close(rfd);
    ifstream ifs(FILENAME);
    cout << "open fifo success..." << endl;
    string msg;
    while (1)
    {
        //y由于C++IO的某种原因，这里ifs不会主动阻塞。导致读端关闭不能持续打印。
        //且关闭写端之后，再次打开写端不能继续写入。目前没有找到缘由
        //因此关闭后再打开，能有阻塞效果
        //且不会出现，打印无关因素
        if(ifs.eof())
        {
            ifs.close();
            ifs.open(FILENAME);
            continue;
        }
        ifs >> msg;
        cout << msg;
        cout.flush();
    }
    ifs.close();
    cout << "close fifo success..." << endl;
    return 0;
}